﻿namespace Anurgath.Shoutbox.Services
{
    #region Usings
    using Anurgath.Shoutbox.Models;
    using Orchard;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using Orchard.ContentManagement;
    using Orchard.Localization;
    using Orchard.Environment;
    #endregion

    public class PostService : IPostService
    {
        #region Private variables
        private readonly Work<IOrchardServices> _OrchardServices;
        #endregion

        #region Constructors
        public PostService(Work<IOrchardServices> orchardServices)
        {
            _OrchardServices = orchardServices;
        }
        #endregion

        #region Properties
        public Localizer T
        {
            get;
            set;
        }
        #endregion

        #region IPostService methods
        public IEnumerable<PostPart> GetAllPostsForShoutbox(int shoutboxId)
        {
            var Result = _OrchardServices.Value.ContentManager.Query<PostPart>().Where<PostPartRecord>(g => g.ParentShoutbox.Id == shoutboxId);
            return Result.List().ToList();
        }

        public PostPart PublishPost(int userId, ShoutboxPart shoutboxPart, string content)
        {
            if (shoutboxPart == null)
            {
                throw new ArgumentNullException("shoutboxPart");
            }

            var NewPostContentItem = _OrchardServices.Value.ContentManager.Create("ShoutboxPost");

            if (NewPostContentItem == null)
            {
                throw new OrchardException(T(TextConsants.ConstContentItemIsNull));
            }

            var PostPart = NewPostContentItem.As<PostPart>();

            if (PostPart == null)
            {
                throw new OrchardException(T(TextConsants.ConstContentPartIsNull));
            }

            PostPart.Content = content;
            PostPart.UserId = userId;
            PostPart.ParentShoutbox = shoutboxPart.Record;
            PostPart.AddDate = DateTime.Now;

            _OrchardServices.Value.ContentManager.Create(NewPostContentItem);

            return PostPart;
        }
        #endregion        
   
    }
}